/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { payment } from "@mall/api-services"
import * as _ from "lodash"
import * as qs from "qs"
import * as React from "react"
import { RouteComponentProps, withRouter } from "react-router"
import Button from "../components/button"
import Checkbox from "../components/checkbox"
import Divider from "../components/divider"
import Flex from "../components/flex"
import NavBar from "../components/navbar"
import ProductPrice from "../components/product/product-price"
import Icon from "../icon"
import "./order-payments.scss"

interface OrderPaymentsProps extends RouteComponentProps {

}

interface OrderPaymentsState {
  provider: payment.PaymentProviderType;
}

class OrderPayments extends React.Component<OrderPaymentsProps, OrderPaymentsState> {

  public constructor(props: Readonly<OrderPaymentsProps>) {
    super(props)
    this.state = {
      provider: payment.PaymentProviderType.AliPay,
    }

    this.handlePayment = this.handlePayment.bind(this)
  }

  public render() {
    const { history } = this.props
    const { provider } = this.state
    const { PaymentProviderType } = payment
    const displayAmount = this.displayAmount

    return (
      <div className="order-payments">
        <NavBar left={<Icon onClick={() => history.goBack()}
                            type="left"/>}>收银台</NavBar>
        <div className="order-payments-content">
          <Flex justifyContent="center" className="total-amount">
            <ProductPrice price={displayAmount} size={28}/>
          </Flex>
          <Divider/>
          <Flex className="payment-providers" direction="column">
            <Flex className="payment-provider" direction="row" justifyContent="space-between"
                  onClick={() => this.setState({ provider: PaymentProviderType.AliPay })}>
              <Flex direction="row" alignItems="center">
                <Icon type="alipay"/>
                <span className="alipay-name">支付宝</span>
              </Flex>
              <Checkbox checked={provider === PaymentProviderType.AliPay}/>
            </Flex>
            <Divider variant="middle"/>
            <Flex className="payment-provider" direction="row" justifyContent="space-between"
                  onClick={() => this.setState({ provider: PaymentProviderType.WxPay })}>
              <Flex direction="row" alignItems="center">
                <Icon type="wxpay"/>
                <span className="wxpay-name">微信支付</span>
              </Flex>
              <Checkbox checked={provider === PaymentProviderType.WxPay}/>
            </Flex>
          </Flex>
        </div>
        <Flex className="order-payments-footer"
              direction="column"
              justifyContent="center">
          <Button type="primary" shape="circle"
                  className="capture-payment-button"
                  onClick={this.handlePayment}>{this.renderPayButtonText()}</Button>
        </Flex>
      </div>
    )
  }

  private renderPayButtonText() {
    const { provider } = this.state
    const texts: any[] = []
    const { PaymentProviderType } = payment
    if (provider === PaymentProviderType.AliPay) {
      texts.push("支付宝支付")
    } else if (provider === PaymentProviderType.WxPay) {
      texts.push("微信支付")
    }
    texts.push(" ¥")
    texts.push(this.displayAmount)
    return texts
  }

  private parseQueryParams() {
    const { location } = this.props
    return qs.parse(location.search.split("?")[1])
  }

  private get displayAmount(): string {
    const amount = this.amount
    return _.isInteger(amount) ? `${amount}.00` : `${amount}`
  }

  private get amount(): number {
    return _.toNumber(this.parseQueryParams()["amount"])
  }

  private get orderIds(): string {
    return this.parseQueryParams()["orders"]
  }


  private handlePayment() {
    const { provider } = this.state
    const newPayment = new payment.Payment()
    newPayment.source = new payment.PaymentSource()
    newPayment.source.type = provider
    newPayment.reference = this.orderIds
    newPayment.amount = this.amount
    payment.PaymentServiceV1.createPayment(newPayment)
      .then(payment => {
        window.open(payment["_links"].redirect.href, "_blank")
      })
    // order.OrderServiceV1.createPaymentOrder(paymentOrder)
    //   .then(link => {
    //     window.open(link.url, "_blank ")
    //   })
  }
}

export default withRouter(OrderPayments)
